import { ref, reactive, toRefs } from "vue";

type tableParams = {
  pageNum: number;
  pageSize: number;
};

export default function useTable<
  T extends { list: any[]; total: number },
  P extends tableParams = tableParams
>(api: (params: P) => RES<T>, searchParams?: Object) {
  const list = ref<T["list"]>([]);

  const total = ref<number>(0);
  const params = reactive<tableParams>({
    pageNum: 1,
    pageSize: 10,
  });
  const fetch = () => {
    api({ ...(params as P), ...searchParams }).then((res) => {
      if (res.code === 200) {
        list.value = res.data.list;
        total.value = res.data.total;
      }
    });
  };
  fetch();
  //页数
  const pageNumChange = () => {
    fetch();
  };
  //页码
  const pageSizeChange = () => {
    fetch();
  };
  //搜索
  const searchChange = () => {
    fetch();
  };
  return {
    list,
    total,
    ...toRefs(params),
    pageNumChange,
    pageSizeChange,
    searchChange,
  };
}
